const GET_OPENID_URL = 'https://www.youngcr.cn/capi/user/openid'

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

/**
 * @description 请求后端接口，返回openid信息
 * @returns { Promise } OPEN_ID
 */
const getOpenid = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        console.log(res.code)
        if (res.code) {
          wx.showLoading({ mask: true, title: '获取中···' })
          wx.request({
            url: GET_OPENID_URL,
            method: 'GET',
            data: {
              code: res.code
            },
            success(result) {
              resolve(result.data.openid)
            },
            fail(err) {
              reject(err)
            },
            complete() {
              wx.hideLoading()
            }
          })
        } else {
          reject('登录失败')
        }
      },
      fail() {
        reject('调用wx.login失败')
      }
    })  
  })


  return openid
}

/**
 * @description 返回随机字符串
 * @param { Number } length 随机字符串长度
 * @param { Boolean } upper 是否大写 
 * @returns { String } 指定长度随机字符串(默认长度5, 小写)
 */
const randomString = (length = 5, upper = false) => {
  let str = (Math.random()).toString(32).slice(2, 2 + length)
  if (upper) {
    str = str.toUpperCase()
  }
  return str
}

export {
  formatTime,
  formatNumber,
  getOpenid,
  randomString
}
